/***************************************************************************
 * 
 * Copyright (c) 2012 Baidu.com, Inc. All Rights Reserved
 * common.h,v 1.0 2012-09-01 15:14 yelu01
 * 
 **************************************************************************/
 
 
 
/**
 * @file skiplist.h
 * @author yelu01(yelu01@baidu.com)
 * @date 2012-08-17 11:30
 * @version 1.0 
 * @brief macros to do type cast, output err info on failed.
 * @thread safety. object level safe.
 *  
 **/

#pragma once

#include <vector>
#include "item.h"
#include "iterator.h"
#include "mutex.h"
#include "log.h"

struct node_t;
typedef node_t* pnode;
typedef pnode* pnode_arr;

struct node_t
{
	node_t();
	pitem item;					// pointer to item.
	pnode_arr nexts;	// array of pointer to next.
};

class mem_matrix_t
{
public:
	friend class mem_matrix_iterator_t;
	mem_matrix_t(comparator row_cmp = bytes_t::raw_comparator,
			comparator col_cmp = bytes_t::raw_comparator);
	~mem_matrix_t();
	int create();
	int insert(const pitem& item);
	int find(const bytes_t& row, std::vector<pitem>& res);

	static uint64_t get_curr_time_us();
private:
	uint32_t _gen_random_height();
	comparator _row_cmp;
	comparator _col_cmp;
	uint32_t _height;
	pnode _head;
	static const uint32_t _max_level_cnt = 12;	// Refer to leveldb.
	uint64_t _size;
	mutex_t _mutex;			// Allow only one writer. It will not block readers.
};

class mem_matrix_iterator_t:public iterator_t
{
public:

	mem_matrix_iterator_t(mem_matrix_t& mem_matrix);

	int reset();

	int get_next(pitem& item);

	uint64_t size();

private:
	mem_matrix_t& _mem_matrix;
	comparator _row_cmp;
	comparator _col_cmp;
	pnode _curr_node;
	bool _is_reset;
};

